package me.leiusual.sharing.ui.cart

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import kotlinx.android.synthetic.main.fragment_cart_order.*
import kotlinx.android.synthetic.main.view_holder_mine_address.view.*
import kotlinx.coroutines.Job
import me.leiusual.sharing.R
import me.leiusual.sharing.api.model.OrderCheckout
import me.leiusual.sharing.repository.model.Data
import me.leiusual.sharing.ui.MainViewModel
import me.leiusual.sharing.ui.base.AbstractFragment
import me.leiusual.sharing.ui.base.AbstractViewModel
import me.leiusual.sharing.ui.cart.adapter.CartOrderParentAdapter
import me.leiusual.sharing.ui.helper.HandleObserver
import me.leiusual.sharing.util.extension.spToPx
import me.leiusual.sharing.util.extension.toJson
import me.leiusual.sharing.util.extension.toSpanned
import me.leiusual.sharing.util.extension.toast
import timber.log.Timber
import javax.inject.Inject

/**
 * author: leiusual
 * create on: 2019-07-28
 * description:
 */
class CartOrderFragment : AbstractFragment(), View.OnClickListener {

  @Inject
  lateinit var factory: ViewModelProvider.Factory

  private val mainViewModel: MainViewModel by activityViewModels { factory }

  private val viewModel: CartOrderViewModel by viewModels { factory }

  override val abstractViewModel: AbstractViewModel
    get() = viewModel

  private var payJob: Job? = null

  override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    return inflater.inflate(R.layout.fragment_cart_order, container, false)
  }

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    toolbar.setNavigationOnClickListener {
      findNavController().popBackStack()
    }

    text_view_address.setOnClickListener(this)
    include_view_holder_mine_address.setOnClickListener(this)

    recycler_view.adapter = CartOrderParentAdapter()

    button_confirm.setOnClickListener(this)

    observeData()
    @Suppress("UNCHECKED_CAST")
    val cartIdQuantity = arguments?.getSerializable("cartIdQuantity") as HashMap<Long, Int>
    viewModel.orderConfirm(cartIdQuantity)
  }

  override fun onDestroyView() {
    super.onDestroyView()

    // 取消
    payJob?.cancel()
  }

  private fun observeData() {
    mainViewModel.address.observe(viewLifecycleOwner, Observer {
      Timber.v("address = %s", it)
      if (it == null) {
        text_view_address.isVisible = true
        include_view_holder_mine_address.isVisible = false

      } else {
        text_view_address.isVisible = false
        include_view_holder_mine_address.isVisible = true

        // 显示地址信息
        include_view_holder_mine_address.text_view_name.text = it.linkMan
        include_view_holder_mine_address.text_view_phone.text = it.contactPhone
        include_view_holder_mine_address.text_view_default.isVisible = it.defaulted
        include_view_holder_mine_address.text_view_address.text = it.provCityCounty + it.detailAddress
        include_view_holder_mine_address.image_button_edit.setImageResource(R.drawable.ic_nav_arrow)
      }
    })

    viewModel.orderConfirm.observe(viewLifecycleOwner, HandleObserver {
      Timber.v("orderConfirm = %s", it)
      when (it) {
        is Data.Loading -> {
          state_constraint_layout.showProgress()
        }
        is Data.Error -> {
          state_constraint_layout.showError(it.error.message)
        }
        is Data.Success -> {
          state_constraint_layout.showContent()

          // 默认地址
          val address = it.data.defaultAddress?.toAddress()
          if (mainViewModel.address.value == null && address != null) {
            mainViewModel.address(address)
          }

          // 更新列表
          val adapter = recycler_view.adapter as CartOrderParentAdapter
          adapter.submitList(it.data.carts)

          // 支付方式
          it.data.payModes.entries.forEach { entry ->
            when (entry.key) {
              "WX_PAY" -> {
                radio_button_wechat.isVisible = true
              }
              "ALI_PAY" -> {
                radio_button_alipay.isVisible = true
              }
            }
          }

          // 费用合计
          val size = 10f.spToPx(requireContext())
          val builder = StringBuilder()
          builder.append("""<font color="red">""")
          it.data.totalPriceVos.forEach { totalPriceVo ->
            when (totalPriceVo.coinType) {
              "RMB" -> builder.append("""<size_$size>￥</size_$size>""")
              else -> builder.append("""  <size_$size>分</size_$size>""")
            }
            builder.append(totalPriceVo.pointCoinString)
          }
          builder.append("""</font>""")
          text_view_total.text = builder.toString().toSpanned()
        }
      }
    })

    viewModel.orderCheckout.observe(viewLifecycleOwner, HandleObserver {
      Timber.v("orderCheckout = %s", it)
      when (it) {
        is Data.Loading -> {
          button_confirm.isEnabled = false
        }
        is Data.Error -> {
          button_confirm.isEnabled = true
          toast(it.error.message)
        }
        is Data.Success -> {
          button_confirm.isEnabled = true

          // 根据选择的支付方式去支付
          when (viewModel.orderCheckoutParams.value?.payType) {
            "WX_PAY" -> {
              doPayByWeChat(it.data)
            }
            "ALI_PAY" -> {
              doPayByAlipay(it.data)
            }
          }
        }
      }
    })

    viewModel.paySuccess.observe(viewLifecycleOwner, HandleObserver {
      Timber.v("paySuccess %s", it)

      // 支付成功，转到订单列表
      val navDirections = CartOrderFragmentDirections.actionCartOrderFragmentToOrderHomeFragment(3, 0)
      findNavController().navigate(navDirections)
    })
  }

  override fun onClick(v: View?) {
    when (v?.id) {
      R.id.text_view_address, R.id.include_view_holder_mine_address -> {

        // 选择地址
        val action = CartOrderFragmentDirections.actionCartOrderFragmentToMineAddressFragment(true)
        findNavController().navigate(action)
      }
      R.id.button_confirm -> {

        // 提交订单
        doOrderCheckout()
      }
    }
  }

  private fun doOrderCheckout() {

    // 发货地址
    val address = mainViewModel.address.value
    if (address == null) {
      toast("请选择地址")
      return
    }

    // 购物车信息
    @Suppress("UNCHECKED_CAST")
    val cartIdQuantity = arguments?.getSerializable("cartIdQuantity") as HashMap<Long, Int>
    val json = cartIdQuantity.toJson()
    if (json == null) {
      toast("无购物车信息")
      return
    }

    // 支付方式
    val payType = when (radio_group.checkedRadioButtonId) {
      R.id.radio_button_wechat -> "WX_PAY"
      R.id.radio_button_alipay -> "ALI_PAY"
      else -> {
        toast("无可用支付方式")
        return
      }
    }

    // 其他信息
    val other = mutableMapOf<String, String>()
    val data = viewModel.orderConfirm.value as? Data.Success
    data?.data?.carts?.forEach {
      other["orderMemo_${it.storeId}"] = it.memo ?: ""
    }

    // 提交支付订单
    val request = OrderCheckout.Request(
        address.id,
        "",
        payType,
        json,
        other
    )
    viewModel.orderCheckout(request)
  }
}